package com.xls.commonlibrary.http.biz;

import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BN_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BN_TEST_INDEX;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BP_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_BP_TEST_INDEX;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_INFOSTREAM_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_INFOSTREAM_TEST_INDEX;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_JL_TEST_INDEX;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_JL_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_KP_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_KP_TEST_INDEX;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_QP_TEST;
import static com.xls.commonlibrary.constant.Const.HYLC_XXL_QP_TEST_INDEX;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.webkit.ValueCallback;

import androidx.appcompat.app.AppCompatActivity;

import com.hjq.toast.Toaster;
import com.orhanobut.logger.Logger;
import com.xls.commonlibrary.BuildConfig;
import com.xls.commonlibrary.R;
import com.xls.commonlibrary.ad.adn.gm.GMPreloadUtil;
import com.xls.commonlibrary.app.MainApplication;
import com.xls.commonlibrary.bean.AdCodeResult;
import com.xls.commonlibrary.http.Api;
import com.xls.commonlibrary.http.RetrofitHelper;
import com.xls.commonlibrary.http.RxLifecycle;
import com.xls.commonlibrary.http.Transformer;
import com.xls.commonlibrary.util.MMKVUtil;
import com.xls.commonlibrary.util.cache.ACache;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Nonnull;

// 广告位  轮询工具
public class CodeRewardUtil {
    private static volatile CodeRewardUtil singleton = null;

    private CodeRewardUtil() {
    }

    public static CodeRewardUtil getInstance() {
        if (singleton == null) {
            synchronized (CodeRewardUtil.class) {
                if (singleton == null) {
                    singleton = new CodeRewardUtil();
                }
            }
        }
        return singleton;
    }

    int freshTime = 1 * ACache.TIME_HOUR;

    // get current id
    public String getAdId(String keyTag, String indexTag) {
        String adid = "";
        ArrayList<AdCodeResult> ads =
                (ArrayList<AdCodeResult>) ACache.get(MainApplication.getAppContext()).getAsObject(keyTag);

        if (ads == null || ads.size() < 1) {
            Logger.d("========getAdId====广告位列表为空！！！key=%s",keyTag);

            if (TextUtils.isEmpty(adid)) {
//                Toaster.show("广告位id为空");
            }

            return adid;
        }

        // 当前索引
        int index = MMKVUtil.getInstance().getKV().decodeInt(indexTag, 0);

        adid = ads.get(index).getAd_code();

        Logger.d("========getAdId====adid:%s", adid);

        // 索引+1   循环   更新
        int indexNew = (index + 1) % ads.size();
        Logger.d("========getAdId===ads Size:%d=====indexNew:%d====", ads.size(), indexNew);
        MMKVUtil.getInstance().getKV().encode(indexTag, indexNew);


        return adid;

    }


    // 是否需要更新
    public boolean isNeedUpdate() {
        ArrayList<AdCodeResult> ads =
                (ArrayList<AdCodeResult>) ACache.get(MainApplication.getAppContext()).getAsObject(HYLC_XXL_JL_TEST);

        // 没有激励id就需要重新拉数据
        if (ads == null || ads.size() < 1) {
            Logger.d("========getAdId====广告位列表为空！！！");
            Logger.d("========getAdId====广告位列表为空！！！");
            return true;
        }

        return false;
    }


    @SuppressLint("CheckResult")
    public void getAdCodeAll(// 获取全部广告位
                             @Nonnull AppCompatActivity activity,
                             @Nonnull ValueCallback<Boolean> callback
    ) {

        Map<String, String> data = new HashMap<>();
//        data.put("packageCode", activity.getString(R.string.ad_package_code_test));//测试广告位id
//        data.put("packageCode", activity.getString(R.string.ad_package_code_release));//正式广告位id
        data.put("packageCode", BuildConfig.AD_PACKAGE_CODE);
        data.put("companyCode", BuildConfig.AD_COMPANY_CODE);
//        data.put("companyCode", activity.getString(R.string.ad_company_code));

        RetrofitHelper.getInstance()
                .create(Api.class)
                .getAdcodeList(data)
                .compose(Transformer.transform())
                .compose(RxLifecycle.bindRxLifecycle(activity))
                .subscribe(
                        result -> {
                            Logger.d("=====getAdCodeAll=======" + result.getData().toString());

                            if (callback != null) {
                                if (result.getData() != null
                                        && result.getData().getHYLC_XXL_JL_TEST() != null
                                        && result.getData().getHYLC_XXL_JL_TEST().size() > 0) {
                                    // 存五个类型广告位数组

                                    // save ads here  有效期XXXXh
                                    ACache.get(MainApplication.getAppContext()).put(HYLC_XXL_JL_TEST, result.getData().getHYLC_XXL_JL_TEST(), freshTime);
                                    ACache.get(MainApplication.getAppContext()).put(HYLC_XXL_KP_TEST, result.getData().getHYLC_XXL_KP_TEST(), freshTime);
                                    ACache.get(MainApplication.getAppContext()).put(HYLC_XXL_QP_TEST, result.getData().getHYLC_XXL_QP_TEST(), freshTime);
                                    ACache.get(MainApplication.getAppContext()).put(HYLC_XXL_BP_TEST, result.getData().getHYLC_XXL_BP_TEST(), freshTime);
                                    ACache.get(MainApplication.getAppContext()).put(HYLC_XXL_BN_TEST, result.getData().getHYLC_XXL_BN_TEST(), freshTime);
                                    ACache.get(MainApplication.getAppContext()).put(HYLC_XXL_INFOSTREAM_TEST, result.getData().getHYLC_XXL_INFOSTREAM_TEST(), freshTime);

                                    // 重置 索引
                                    MMKVUtil.getInstance().getKV().encode(HYLC_XXL_JL_TEST_INDEX, 0);
                                    MMKVUtil.getInstance().getKV().encode(HYLC_XXL_KP_TEST_INDEX, 0);
                                    MMKVUtil.getInstance().getKV().encode(HYLC_XXL_QP_TEST_INDEX, 0);
                                    MMKVUtil.getInstance().getKV().encode(HYLC_XXL_BP_TEST_INDEX, 0);
                                    MMKVUtil.getInstance().getKV().encode(HYLC_XXL_BN_TEST_INDEX, 0);
                                    MMKVUtil.getInstance().getKV().encode(HYLC_XXL_INFOSTREAM_TEST_INDEX, 0);

                                    Logger.d("=======getAdCodeAll==广告id缓存成功=====");
                                    callback.onReceiveValue(true);
                                } else {
                                    callback.onReceiveValue(false);
                                }
                            }


                        },
                        throwable -> {
                            Logger.d(throwable);
                        }
                );

    }

    /**
     * 预加载  广告
     *
     * @param activity
     * @param keyTag
     */
    public void preloadAd(AppCompatActivity activity) {
        ArrayList<AdCodeResult> adsJH =
                (ArrayList<AdCodeResult>) ACache.get(MainApplication.getAppContext()).getAsObject(HYLC_XXL_JL_TEST);
        ArrayList<AdCodeResult> adsBP =
                (ArrayList<AdCodeResult>) ACache.get(MainApplication.getAppContext()).getAsObject(HYLC_XXL_BP_TEST);



        GMPreloadUtil.getInstance().mediationPreloadAds(activity, adsJH, adsBP);

    }
}
